package cz.schovjan.proj.controllers;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import cz.schovjan.proj.dto.Concert;
import cz.schovjan.proj.service.IConcert;

/**
 * Kontroler pro editaci/detail koncertu.
 * @author schovjan
 *
 */
@Controller
@RequestMapping("/concert")
@SessionAttributes({"band","user"}) //user se musi uvest taky, jinak se nepouzije
public class ConcertController extends Base {

	/** stranka s detailem koncertu */
	private static final String CONCERT_DETAIL = "detailConcert";	
	
	/** Service pro koncerty.	 */
	@Autowired
	private IConcert concerts;
	
	
	/////////////////
	//OBSLUZNE FUKNCE ------------------------------------------------------------
	/////////////////
	
	
	/**
	 * Zobrazi detail koncertu.
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/detail")
	public String detail(@RequestParam("id") int id, ModelMap model) {
		Concert c = concerts.find(id);
		model.addAttribute("concert", c);
		model.addAttribute("edit", false);
		
		return CONCERT_DETAIL;
	}
	
	
	/**
	 * Zobrazi editaci koncertu.
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/edit")
	public String edit(@RequestParam("id") int id, ModelMap model) {
		Concert c = concerts.find(id);
		model.addAttribute("concert", c);
		model.addAttribute("edit", true);
		
		return CONCERT_DETAIL;
	}
	
	
	/**
	 * Ulozeni zmeny pri editaci koncertu.
	 * @param koncert
	 * @param result
	 * @param model
	 * @return
	 */
	@RequestMapping(method=RequestMethod.POST, value="/concertSave")
	public String bandSave(@Valid @ModelAttribute("concert") Concert concert, BindingResult result, ModelMap model) {
		model.addAttribute("edit", true);
		
		if (result.hasErrors()) {
			return CONCERT_DETAIL;
		}
		concerts.save(concert.getId(), 
						concert.getPlace(),
						concert.getDateTime(),
						concert.getDescription());
			
		model.addAttribute("message", MSG_CONCERT_SAVE);
		model.addAttribute("concert", concerts.find(concert.getId()));
				
		return CONCERT_DETAIL;
	}
	
}
